package model

import (
	"server/global"

	"gorm.io/gorm"
)

type Role struct {
	BaseModel
	Name    string     `gorm:"size:64;default:'';unique;comment:角色名"`
	Code    string     `gorm:"size:32;default:'';unique;comment:角色代码"`
	IsAdmin bool       `gorm:"default:false;comment:是否是超级管理员"`
	Users   []UserRole `gorm:"foreignKey:RoleID;references:ID;comment:角色用户关系"`
	Menus   []RoleMenu `gorm:"foreignKey:RoleID;references:ID;comment:角色菜单关系"`
}

func (r *Role) BeforeCreate(tx *gorm.DB) (er error) {
	if err := r.BaseModel.BeforeCreate(tx); err != nil {
		global.GA_LOGGER.Sugar().Errorw("Role BeforeCreate Error", "error", err.Error())
		return err
	}
	if r.Code == "admin" {
		if result := tx.Model(&r).Update("is_admin", true); result.Error != nil {
			global.GA_LOGGER.Sugar().Errorw("Role BeforeCreate Error", "error", result.Error.Error())
			return result.Error
		}
	}
	return nil
}
